package org.dousb.doupicture.infrastructure.api.aliyunai.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dousb.doupicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskRequest;
import org.dousb.doupicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskRespose;
import org.dousb.doupicture.infrastructure.common.ErrorCode;
import org.dousb.doupicture.infrastructure.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AliYunAiApi {

    //创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    //查询任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    /**
     * 创建扩图任务
     *
     * @param createOutPaintingTaskRequest
     * @return
     */
    public CreateOutPaintingTaskRespose createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        if (createOutPaintingTaskRequest == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "扩图参数为空");
        }

        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer" + apiKey)
                //开启异步处理
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("创建扩图任务失败, 响应状态码: {}, 响应体: {}", httpResponse.getStatus(), httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI扩图失败");
            }
            CreateOutPaintingTaskRespose response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskRespose.class);
            String errCode = response.getOutput().getCode();
            if (StrUtil.isNotBlank(errCode)) {
                log.error("创建扩图任务失败, 错误码: {}, 错误信息: {}", errCode, response.getOutput().getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI扩图接口响应异常, 错误码: " + errCode + ", 错误信息: " + response.getOutput().getMessage());
            }
            return response;
        }
    }

    /**
     * 查询扩图任务状态
     *
     * @param taskId
     * @return
     */
    public CreateOutPaintingTaskRespose getOutPaintingTask(String taskId) {
        if (StrUtil.isBlankIfStr(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务ID为空");
        }

        try (HttpResponse httpResponse = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer" + apiKey)
                .execute()) {
            if (!httpResponse.isOk()) {
                log.error("查询扩图任务状态失败, 响应状态码: {}, 响应体: {}", httpResponse.getStatus(), httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务获取失败");
            }
            return JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskRespose.class);
        }
    }

}
